package com.boot2.core.utils;

import org.apache.commons.lang3.SerializationUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangweilin
 * @version V1.0
 * @date 2017年1月10日 下午4:59:25
 * @description 基于base64的序列化, 但是返回的不是base64串
 */
public class Base64SerializeUtils extends SerializationUtils {

    public static String serializeToString(Serializable obj) {
        try {
            byte[] value = serialize(obj);
            return Base64Util.encodeToString(value);
        } catch (Exception e) {
            throw new RuntimeException("serialize  error", e);
        }
    }

    public static <T> T deserializeFromString(String base64) {
        try {
            byte[] objectData = Base64Util.decode(base64);
            return deserialize(objectData);
        } catch (Exception e) {
            throw new RuntimeException("deserialize  error", e);
        }
    }

    public static <T> Collection<T> deserializeFromStringController(Collection<String> base64s) {
        try {
            // List<T> list = Lists.newLinkedList();
            List<T> list = new LinkedList<>();
            for (String base64 : base64s) {
                byte[] objectData = Base64Util.decode(base64);
                T t = deserialize(objectData);
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException("deserialize   error", e);
        }
    }
}
